package com.example.demo.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    private final DefaultKaptcha defaultKaptcha;

    @Autowired
    public CaptchaController(DefaultKaptcha defaultKaptcha) {
        this.defaultKaptcha = defaultKaptcha;
    }

    @GetMapping
    public ResponseEntity<byte[]> getCaptcha(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        // 生成验证码文本
        String captchaText = defaultKaptcha.createText();
        // 根据文本生成验证码图片
        BufferedImage captchaImage = defaultKaptcha.createImage(captchaText);

        session.setAttribute(Constants.KAPTCHA_SESSION_KEY, captchaText);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_PNG);

        // 将图片转换为字节数组并返回给前端
        try {
            java.io.ByteArrayOutputStream os = new java.io.ByteArrayOutputStream();
            javax.imageio.ImageIO.write(captchaImage, "png", os);
            return new ResponseEntity<>(os.toByteArray(), headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}